package com.sky.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UploadResultDTO;
import com.sky.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Api(tags = "文件上传")
@RestController
@RequestMapping("/admin/common")
@Slf4j
public class CommonController {

    @Autowired
    private RestTemplate restTemplate;

    @PostMapping("/upload")
    @ApiOperation("图像上传")
    public Result<String> imageUpload(MultipartFile file) throws IOException {
        log.info("图像上传：{}", file.getOriginalFilename());

        // 上传数据准备
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("image", new ByteArrayResource(file.getBytes()) {
            @Override
            public String getFilename() {
                return file.getOriginalFilename();
            }
        });

        // 请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

        // 发送请求
        String url = "http://localhost:3090/uploadImage";
        ResponseEntity<UploadResultDTO> response = restTemplate.postForEntity(url, requestEntity, UploadResultDTO.class);

        // 处理响应
        if (response.getStatusCode().is2xxSuccessful()) {
            UploadResultDTO uploadResultDTO = response.getBody();
            return Result.success(uploadResultDTO != null?(String) uploadResultDTO.getData():"DTO is null");
        } else {
            return Result.error("上传至云端错误：" + response.getStatusCodeValue());
        }
    }
}
